const Koa = require('koa');
const logger = require('koa-logger');
const compress = require('koa-compress');
const KoaStatic = require('koa-static');
const ReactDOMServer = require('react-dom/server');
const config = require('../webpack.server.config');
const Router = require('koa-router');
const path = require("path");
const fs = require('fs');
const {createApp} = require('../src/server');

const app = new Koa();
const router = new Router();

// 日志打印
app.use(logger());

// 使用静态资源
app.use(KoaStatic(path.join(__dirname, "../dist")));

// 压缩数据
app.use(compress({
  filter(content_type) {
    return /text/i.test(content_type)
  },
  threshold: 1024,  //超过1KB压缩
  gzip: {
    flush: require('zlib').constants.Z_SYNC_FLUSH
  },
  deflate: {
    flush: require('zlib').constants.Z_SYNC_FLUSH,
  },
  br: false // disable brotli
}))

// 捕获异常，返回错误页面
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (e) {
    ctx.type = 'text/html; charset=utf-8'
    ctx.body = '<div>error</div>'
    //释放error，让监听函数生效
    ctx.app.emit('error', e, ctx);
  }
});

// 监听异常
app.on('error', err => {
  console.error('服务异常', err)
});

let template = fs.readFileSync("./dist/index.html", "utf-8");
const service = require('../src/service/hero');

// 对于任何请求，app将调用该异步函数处理请求
router.all('(.*)', async (ctx, next) => {
  console.log('ctx.request.url', ctx.request.url)
  // 设置response的Content-Type:
  ctx.response.type = 'text/html; charset=utf-8';
  const res = await service.heroList();
  console.log("请求结果", res);
  // 设置response的内容:
  let context = {}
  const serverEntry = createApp(context, ctx.request.url);
  let html = ReactDOMServer.renderToString(serverEntry);
  let htmlStr = template.replace("<div id=\"root\"></div>", `<div id='root'>${html}</div> <script type="text/javascript">window.INITIAL_DATA=${JSON.stringify(res.data)}</script>`);
  if(context.url) {
    ctx.redirect(context.url);
  } else {
    console.log('context', context)
    if(context.status) {
      ctx.response.status = 404;    
    }
    ctx.response.body = htmlStr;
  }
});

app.use(router.routes());
app.use(router.allowedMethods());

app.listen(3000);
console.log('app started at port 3000...');